package com.hup.minicontroller.server.auth;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;

import com.hup.minicontroller.server.ServerApplication;
import com.hup.minicontroller.server.mvp.ICursorFloaterView;
import com.hup.minicontroller.server.service.CursorFloaterService;

/**
 * {@link CursorFloaterService} 的[悬浮窗权限]申请工具类<pre>
 * 权限:
 * <uses-permission  android:name="android.permission.SYSTEM_ALERT_WINDOW" />
 * 悬浮窗权限资料:
 * https://www.jianshu.com/p/6e0ded76fa4c
 * https://blog.csdn.net/self_study/article/details/52859790
 *
 * @author hugan
 * @date 2021/5/8
 */
public abstract class FloaterAuthForCFS {
    private static final String TAG = FloaterAuthForCFS.class.getSimpleName();
    public static int REQUEST_CODE_FLOATER = 24587;

    @SuppressWarnings("BooleanMethodIsAlwaysInverted")
    public static boolean hasAuth() {
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true;//<6.0的
        return Settings.canDrawOverlays(ServerApplication.getContext());
    }

    /**
     * 使用Activity请求权限
     *
     * @param activity 必须重写handleActivityResult并调用 {@link #handleActivityResult(int, int, Intent, Activity)}
     */
    public static void acquireFloaterAuthForService(Activity activity) {
        Log.i(TAG, "acquireFloaterAuthForService: 开始申请权限");
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + "com.hup.minicontroller.server"));
        activity.startActivityForResult(intent, REQUEST_CODE_FLOATER);
    }

    /**
     * 处理权限申请的返回结果
     *
     * @return 是否处理消息, true-已处理,是本类的请求结果;false-没处理,不是本类的请求结果
     */
    @SuppressWarnings("unused")
    public static boolean handleActivityResult(int requestCode, int resultCode, Intent data, Activity activity) {
        if (requestCode != REQUEST_CODE_FLOATER) return false;
//        if (resultCode == Activity.RESULT_OK) {
//            Log.e(TAG, "handleActivityResult: 用户允许悬浮窗权限");
//        } else {
//            Log.e(TAG, "handleActivityResult: 用户拒绝悬浮窗权限");
//        }
        ServerApplication.getBean(ICursorFloaterView.class).acquireFloaterAuthResult();
        return true;
    }
}
